package job

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/service/redis_ser"
	"github.com/sirupsen/logrus"
)

type articleJob struct {
}

func (a articleJob) Run() {
	logrus.Info("执行文章定时任务")
	digg := redis_ser.NewArticleDigg()
	look := redis_ser.NewArticleLook()
	diggMap := digg.DiggGetAll()
	lookMap := look.DiggGetAll()
	var list []articleCount
	// 这样只会查询这个结构体中的两个对象
	global.DB.Model(&models.ArticleModel{}).Find(&list)
	redisDiggVal := make(map[uint]int)
	redisLookVal := make(map[uint]int)
	for _, info := range list {
		diggCount := diggMap[info.ID]
		lookCount := lookMap[info.ID]
		redisDiggCount := info.DiggCount
		redisLookCount := info.LookCount
		if diggCount > info.DiggCount {
			redisDiggCount = diggCount
			global.DB.Model(&models.ArticleModel{}).Update("digg_count", diggCount)
		}
		if lookCount > info.LookCount {
			redisLookCount = lookCount
			global.DB.Model(&models.ArticleModel{}).Update("look_count", lookCount)
		}
		redisDiggVal[info.ID] = redisDiggCount
		redisLookVal[info.ID] = redisLookCount
	}
	digg.DiggSetAll(redisDiggVal)
	look.DiggSetAll(redisLookVal)
	logrus.Info("文章定时任务执行结束")
}

type articleCount struct {
	ID        uint // id
	DiggCount int  // 点赞量
	LookCount int  // 浏览量
}
